import { defineStore } from 'pinia';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import {
  getLoginUserUsingGet,
  userLoginUsingPost,
  userLogoutUsingPost,
} from '@/api/userController';
import useAppStore from '../app';
import UserInfo = API.UserInfo;
import UserLoginRequest = API.UserLoginRequest;

const useUserStore = defineStore('user', {
  state: (): UserInfo => ({
    createTime: undefined,
    id: undefined,
    sex: undefined,
    updateTime: undefined,
    userAvatar: undefined,
    userName: undefined,
    userPermission: undefined,
    userProfile: undefined,
    userRole: undefined,
    vipExpireTime: undefined,
    vipNumber: undefined,
  }),

  getters: {
    userInfo(state: UserInfo): UserInfo {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.userRole = this.userRole === 'user' ? 'admin' : 'user';
        resolve(this.userRole);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserInfo>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await getLoginUserUsingGet();
      this.setInfo(res.data);
    },

    // Login
    async login(loginForm: UserLoginRequest) {
      try {
        const res = await userLoginUsingPost(loginForm);
        // TODO
        setToken(res.data.token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogoutUsingPost();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
